<template>
  <div class="double-line-chart">
    <e-charts ref="chart" :options="options" autoresize @legendselectchanged="legendchanged"/>
  </div>
</template>

<script type="text/javascript">
import ECharts from '@/components/Echarts'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'

import { DATE_TYPE } from '../constant'
import Mixin from '../mixin'
echarts.use([LineChart])
export default {
  name: 'DoubleLineChart',
  mixins: [Mixin],
  components: {
    ECharts
  },
  props: {
    listData: {
      type: Array,
      required: true
    },
    legend: {
      type: Array,
      required: true
    },
    timeRangeNum: Number,
    params: { } // 查询参数
  },
  data () {
    return {
      selectLegend: [],
      options: null
    }
  },
  methods: {
    init () {
      !this.selectLegend.length && (this.selectLegend = ['交易总额', '活跃用户数'])
      this.options = this.getChartOption(this.listData, this.legend, this.selectLegend, this.params)
    },
    // eslint-disable-next-line sonarjs/cognitive-complexity
    getChartOption (list, legend, selectLegend, params) {
      return {
        tooltip: {
          trigger: 'axis',
          formatter: (params1) => {
            let str = `
              <div class="tooltip-wrap">
                <div class="title">${params1[0].axisValueLabel}</div>
            `
            const contrast = list[params1[0].dataIndex].contrast
            params1.forEach(it => {
              str += `<div class="series">
                        <span class="mark" style="background-color:${it.color};"></span>
                        <span class="label">${it.seriesName}</span>
                        <span class="value">${it.value}${it.seriesName.endsWith('率') ? '%' : ''}</span>`
              if (this.timeRangeNum) {
                const value = this.formatNumber(contrast[it.seriesName], it.seriesName)
                str += `<span class="contrast">前${this.timeRangeNum}${params.time_grain_sqla === 'P1D' ? '天' : params.time_grain_sqla === 'P1W' ? '周' : '月'}:${value}${it.seriesName.endsWith('率') ? '%' : ''}</span>
                        <span>（环比 ${contrast[it.seriesName] ? parseInt((it.value - value) / value * 100) : 0}%）</span>`
              }
              str += '</div>'
            })
            str += '</div>'
            return str
          }
        },
        legend: {
          bottom: 0,
          type: 'scroll',
          icon: 'circle',
          data: legend,
          selected: legend.reduce((obj, label) => {
            obj[label] = selectLegend.includes(label)
            return obj
          }, { '交易总额': true })
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: list.map(t => this.fmtTableDate(t.time || t.__timestamp, params.time_grain_sqla)),
          axisLabel: {
            interval: list.length > 15 ? 1 : 0, // 显示所有刻度
            formatter (value) {
              return params.time_grain_sqla === DATE_TYPE.HOUR ? value.slice(11) : value
            }
          }
        },
        yAxis: selectLegend.map((name, index) => ({
          id: index,
          type: 'value',
          name,
          axisLabel: {
            // y轴上带的单位
            formatter: '{value}'
          },
          // 轴线
          axisLine: {
            show: true
          },
          // 分割线
          splitLine: {
            show: false
          }
        })),
        series: list.reduce((arr, item) => {
          for (const key in item) {
            if (key === 'time' || key === '__timestamp' || key === 'contrast') continue
            const it = arr.find(t => t.name === key)
            const val = this.formatNumber(item[key], key)
            if (it) {
              it.data.push(val)
            } else {
              const obj = {
                name: key,
                type: 'line',
                data: [val]
              }
              const index = selectLegend.findIndex(label => label === key)
              index !== -1 && (obj.yAxisIndex = index)
              arr.push(obj)
            }
          }
          return arr
        }, [])
      }
    },
    legendchanged (params) {
      const item = params.name
      if (this.selectLegend.includes(item)) {
        // 只有一项时不允许去除
        this.selectLegend.length !== 1 && (this.selectLegend = this.selectLegend.filter(label => label !== item))
      } else {
        this.selectLegend.push(item)
        this.selectLegend.length > 2 && this.selectLegend.shift()
      }
      this.options = this.getChartOption(this.listData, this.legend, this.selectLegend, this.params)
      this.$emit('legendChang', this.selectLegend)
    }
  },
  watch: {
    listData () {
      this.init()
    }
  }
}
</script>

<style lang="scss" scoped>
.double-line-chart {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
<style lang="scss">
.chart .tooltip-wrap {
    .title {
      margin-bottom: 6px;
    }
  .series {
    .mark {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin-right: 4px;
      border-radius: 50%;
    }
    .value {
      margin-left: 10px;
      font-weight: bold;
      text-align: right;
    }
    .contrast{
      margin-left: 10px;
    }
  }
}
</style>
